package org.wesc.boot.webapi.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * Log显示接口调用信息.
 *
 * @author Wesley Cheung
 * @date 2018/7/24 11:05
 */
@Slf4j
public class LogApiInterceptor implements AsyncHandlerInterceptor {

    /**
     * 预处理: controller之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String uri = request.getRequestURI();
        // 屏蔽访问swagger时显示调用api
        if (!uri.contains("swagger") && !uri.contains("webjars") && !uri.contains("/api/redis")) {
            StringBuilder sb = new StringBuilder();
            sb.append("API Called: ").append(uri);

            Enumeration<String> enums = request.getParameterNames();
            if (enums.hasMoreElements()) {
                sb.append(" - ");
            }
            while (enums.hasMoreElements()) {
                String key = enums.nextElement();
                sb.append("\"").append(key).append("\":").append(
                        request.getParameter(key)).append(", ");
            }
            log.info(sb.toString());
        }
        return true;
    }

    /**
     * 后处理: controller之后，view渲染前
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           @Nullable ModelAndView modelAndView) {
    }

    /**
     * 完毕处理: view渲染后
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) {
    }

    /**
     * 异步处理前
     */
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response,
                                               Object handler) {
    }

}
